package cn.yunhe.dao;

import cn.yunhe.entity.Role;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

@Mapper
public interface RoleDao {

    @Select("select * from role r ,users_role ur where r.id=ur.roleId and userId = #{userId}")
    List<Role> selectRoleByUserId(@Param("id") Integer userId);

    @Select("select * from role where id not in(select ur.roleId from role r ,users_role ur where r.id=ur.roleId and userId = #{userId})")
    List<Role> selectRole(Integer userId);

    @Insert("insert into users_role values (#{userId},#{roleId})")
    void insertUr(Integer userId, Integer roleId);

    @Select("select * from role r ,users_role ur where r.id=ur.roleId and userId = #{userId}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "permissions", javaType = List.class, many =
            @Many(select = "cn.yunhe.dao.PermissionDao.findByRoleId", fetchType = FetchType.LAZY), column = "id")
    })
    List<Role> findById(@Param("id") Integer userId);

    @Select("select * from role")
    List<Role> findAll();

    @Insert("insert into  role values (null,#{roleName},#{roleDesc})")
    void insertRole(Role role);

    @Select("select * from role where id =#{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "permissions", javaType = List.class, many =
            @Many(select = "cn.yunhe.dao.PermissionDao.findByRoleId2", fetchType = FetchType.LAZY), column = "id")
    })
    Role findRoleByIdAndAllPermission(Integer id);

    @Insert("insert into role_permission values (#{permissionId},#{roleId})")
    void addRp(@Param("permissionId") Integer pId, @Param("roleId") Integer roleId);

    @Select("select * from role where id = #{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "permissions", javaType = List.class, many =
            @Many(select = "cn.yunhe.dao.PermissionDao.findByRoleId3"), column = "id")
    })
    Role findRoleById(Integer id);

    @Delete("delete from role_permission where roleId =#{id}")
    void deleteRp(Integer id);

    @Delete("delete from role where id =#{id}")
    void deleteRole(Integer id);

}
